﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using MxWeiXinPF.Common;
using MxWeiXinPF.WeiXinComm;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.AdvancedAPIs.User;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Entities;

namespace MxWeiXinPF.Web
{
    public partial class wxoauth : Page
    {
        private string appid = "";
        private string code = "";
        private string copenid = null;
        protected HtmlForm form1;
        private string p = "0";
        private string pid = "0";
        private string popenid = null;
        public string reurl = "";
        private string secret = "";
        private int shopid = 0x27;
        private int wid = 0x27;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    if (base.Request.UserAgent.ToLower().Contains("micromessenger"))
                    {
                        MxWeiXinPF.BLL.wx_userweixin _userweixin = new MxWeiXinPF.BLL.wx_userweixin();
                        MxWeiXinPF.Model.wx_userweixin model = null;
                        WeiXCommFun fun = new WeiXCommFun();
                        BLL.wx_dt_user_BaseData data = new BLL.wx_dt_user_BaseData();

                        if ((base.Request.QueryString["reurl"] != null) && (base.Request.QueryString["reurl"] != ""))
                        {
                            this.reurl = base.Request.QueryString["reurl"].ToString();
                        }
                        if ((base.Request.QueryString["wid"] != null) && (base.Request.QueryString["wid"] != ""))
                        {
                            this.wid = int.Parse(base.Request.QueryString["wid"].ToString().Trim());
                        }
                        if ((base.Request.QueryString["p"] != null) && (base.Request.QueryString["p"] != ""))
                        {
                            this.p = base.Request.QueryString["p"].ToString().Trim();
                        }
                        if ((base.Request.QueryString["copenid"] != null) && (base.Request.QueryString["copenid"] != ""))
                        {
                            this.copenid = base.Request.QueryString["copenid"].ToString().Trim();
                        }
                        if ((base.Request.QueryString["pid"] != null) && (base.Request.QueryString["pid"] != ""))
                        {
                            this.pid = base.Request.QueryString["pid"].ToString().Trim();
                        }
                        if ((base.Request.QueryString["shopid"] != null) && (base.Request.QueryString["shopid"] != ""))
                        {
                            this.shopid = Convert.ToInt32(Request.QueryString["shopid"]);
                        }
                        if (base.Request["ReturnURL"] != null)
                        {
                            string str2 = base.Request["ReturnURL"].ToString().Split(new char[] { '&' })[1];
                            this.popenid = str2.Split(new char[] { '=' })[1];
                        }
                        if (model == null)
                        {
                            model = _userweixin.GetModel(this.wid);
                        }
                        if (model != null)
                        {
                            this.appid = model.AppId;
                            this.secret = model.AppSecret;
                        }
                        string url = "";
                        string str4 = "";
                        if ((base.Request.QueryString["code"] != null) && (base.Request.QueryString["code"] != ""))
                        {
                            MxWeiXinPF.Model.users modelByOpenID;
                            this.code = base.Request.QueryString["code"].ToString();
                            OAuthAccessTokenResult result = OAuthApi.GetAccessToken(this.appid, this.secret, this.code, "authorization_code");
                            if (result.errcode != ReturnCode.请求成功)
                            {
                                LogHelper.WriteLog(typeof(wxoauth), "获取全局token失败," + result.errmsg);
                            }
                            try
                            {
                                OAuthUser infos = null;
                                try
                                {
                                    infos = OAuthClass.Get_UserInfo(result.access_token, result.openid);
                                }
                                catch (Exception ex2)
                                {
                                    LogHelper.WriteLog(typeof(wxoauth), ex2);
                                    return;
                                }
                                if ((infos != null) && (infos.openid != null) && (infos.openid != ""))
                                {
                                    if (!data.ExistsWidAndOpenid(this.wid, infos.openid))
                                    {
                                        data.addUserInfoOauth(this.wid, infos.openid, infos.nickname, infos.sex, "zh_CN", infos.city, infos.province, infos.country, infos.headimgurl, infos.unionid, this.shopid, this.popenid);
                                    }
                                    else
                                    {
                                        data.updateNoUserInfoOauth(this.wid, infos.openid, infos.nickname, infos.sex, "zh_CN", infos.city, infos.province, infos.country, infos.headimgurl, infos.unionid, this.shopid);
                                    }
                                    modelByOpenID = data.GetModelByOpenID(infos.openid);
                                    this.Session["dt_session_user_info"] = modelByOpenID;
                                    this.Session.Timeout = 0x2d;
                                    if (modelByOpenID == null) //根据ID获取用户失败
                                    {
                                        this.shopid = 39;
                                        LogHelper.WriteLog(typeof(wxoauth), "根据openid未找到用户信息,指派默认店铺,易药宝" + this.shopid); 
                                    }
                                    else
                                    {
                                        this.shopid = modelByOpenID.shopid;
                                    }
                                    AccessTokenResult tokenresult = CommonApi.GetToken(this.appid, this.secret);
                                    UserInfoJson userinfo = UserApi.Info(tokenresult.access_token, result.openid, Language.zh_CN);
                                    data.UpdateUserInfoUnSubscribe(this.wid, infos.openid, userinfo.subscribe);
                                    
                                    if (userinfo.subscribe.Equals("1"))
                                    {
                                        if (this.p.Equals("1"))
                                        {
                                            //url = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/index.aspx?wid=", this.wid, "&openid=", infos.openid, "&shopid=", this.shopid });
                                            if (CheckHasStaticPage(this.shopid))
                                            {
                                                url = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/index_", this.shopid, ".aspx?wid=", this.wid, "&openid=", result.openid, "&shopid=", this.shopid });
                                            }
                                            else
                                            {
                                                url = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/index.aspx?wid=", this.wid, "&openid=", result.openid, "&shopid=", this.shopid });
                                            }
                                            base.Response.Redirect(url);
                                        }
                                        else if (this.p.Equals("2"))
                                        {
                                            str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/cart.aspx?wid=", this.wid, "&openid=", infos.openid, "&shopid=", this.shopid });
                                            base.Response.Redirect(str4);
                                        }
                                        else if (this.p.Equals("3"))
                                        {
                                            str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/userinfo.aspx?wid=", this.wid, "&openid=", infos.openid, "&shopid=", this.shopid });
                                            base.Response.Redirect(str4);
                                        }
                                        else if (this.p.Equals("5"))
                                        {
                                            str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/userqrcode.aspx?wid=", this.wid, "&openid=", infos.openid, "&shopid=", this.shopid });
                                            base.Response.Redirect(str4);
                                        }
                                        else if (this.p.Equals("6"))
                                        {
                                            str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/userratepoints.aspx?wid=", this.wid, "&openid=", infos.openid, "&shopid=", this.shopid });
                                            base.Response.Redirect(str4);
                                        }
                                        else if (this.p.Equals("7"))
                                        {
                                            str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/useryouhuijuan.aspx?wid=", this.wid, "&openid=", infos.openid, "&shopid=", this.shopid });
                                            base.Response.Redirect(str4);
                                        }
                                        else if (this.p.Equals("8"))
                                        {
                                            str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/userchild.aspx?wid=", this.wid, "&openid=", infos.openid, "&copenid=", this.copenid, "&shopid=", this.shopid });
                                            base.Response.Redirect(str4);
                                        }
                                        else if (this.p.Equals("9"))
                                        {
                                            str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/detail.aspx?wid=", this.wid, "&openid=", infos.openid, "&pid=", this.pid, "&shopid=", this.shopid });
                                            base.Response.Redirect(str4);
                                        }
                                    }
                                    else//用户未关注
                                    {
                                        url = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/index.aspx?wid=", this.wid, "&openid=", infos.openid, "&shopid=", this.shopid });
                                        base.Response.Redirect(url);
                                    }
                                }
                                else
                                {
                                    LogHelper.WriteLog(typeof(wxoauth), "未获取到用户信息");
                                    str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/wxoauth.aspx?wid=", this.wid, "&p=", this.p, "&shopid=", this.shopid });
                                    base.Response.Redirect(string.Concat(new object[] { "https://open.weixin.qq.com/connect/oauth2/authorize?appid=", this.appid, "&redirect_uri=", str4, "&response_type=code&scope=snsapi_base&state=", this.wid, "#wechat_redirect" }));
                                }
                            }
                            catch(Exception ex)
                            {
                               // LogHelper.WriteLog(typeof(wxoauth), ex);
                                if ((result.openid != null) && (result.openid != ""))
                                {
                                    modelByOpenID = data.GetModelByOpenID(result.openid);
                                    this.Session["dt_session_user_info"] = modelByOpenID;
                                    this.Session.Timeout = 0x2d;
                                    this.shopid = modelByOpenID.shopid;
                                    if (this.p.Equals("1"))
                                    {
                                        if (CheckHasStaticPage(this.shopid))
                                        {
                                            url = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/index_",this.shopid,".aspx?wid=", this.wid, "&openid=", result.openid, "&shopid=", this.shopid });
                                        }
                                        else {
                                            url = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/index.aspx?wid=", this.wid, "&openid=", result.openid, "&shopid=", this.shopid });
                                        }
                                        
                                        base.Response.Redirect(url);
                                    }
                                    else if (this.p.Equals("2"))
                                    {
                                        str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/cart.aspx?wid=", this.wid, "&openid=", result.openid, "&shopid=", this.shopid });
                                        base.Response.Redirect(str4);
                                    }
                                    else if (this.p.Equals("3"))
                                    {
                                        str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/userinfo.aspx?wid=", this.wid, "&openid=", result.openid, "&shopid=", this.shopid });
                                        base.Response.Redirect(str4);
                                    }
                                    else if (this.p.Equals("5"))
                                    {
                                        str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/userqrcode.aspx?wid=", this.wid, "&openid=", result.openid, "&shopid=", this.shopid });
                                        base.Response.Redirect(str4);
                                    }
                                    else if (this.p.Equals("6"))
                                    {
                                        str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/userratepoints.aspx?wid=", this.wid, "&openid=", result.openid, "&shopid=", this.shopid });
                                        base.Response.Redirect(str4);
                                    }
                                    else if (this.p.Equals("7"))
                                    {
                                        str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/useryouhuijuan.aspx?wid=", this.wid, "&openid=", result.openid, "&shopid=", this.shopid });
                                        base.Response.Redirect(str4);
                                    }
                                    else if (this.p.Equals("8"))
                                    {
                                        str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/userchild.aspx?wid=", this.wid, "&openid=", result.openid, "&copenid=", this.copenid, "&shopid=", this.shopid });
                                        base.Response.Redirect(str4);
                                    }
                                    else if (this.p.Equals("9"))
                                    {
                                        str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/detail.aspx?wid=", this.wid, "&openid=", result.openid, "&pid=", this.pid, "&shopid=", this.shopid });
                                        base.Response.Redirect(str4);
                                    }
                                }
                                else
                                {
                                    str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/wxoauth.aspx?wid=", this.wid, "&p=", this.p, "&copenid=", this.copenid,"&shopid=",this.shopid });
                                    base.Response.Redirect(string.Concat(new object[] { "https://open.weixin.qq.com/connect/oauth2/authorize?appid=", this.appid, "&redirect_uri=", str4, "&response_type=code&scope=snsapi_base&state=", this.wid, "#wechat_redirect" }));
                                }
                            }
                        }
                        else
                        {
                            str4 = string.Concat(new object[] { MyCommFun.getWebSite(), "/wxoauth.aspx?wid=", this.wid, "&p=", this.p, "&copenid=", this.copenid, "&popenid=", this.popenid, "&shopid=", this.shopid });
                            string str5 = OAuthApi.GetAuthorizeUrl(this.appid, str4, "STATE", OAuthScope.snsapi_userinfo, "code");
                            base.Response.Redirect(str5);
                        }
                    }
                }
                catch (Exception ex)
                {
                  //  LogHelper.WriteLog(typeof(wxoauth), ex);
                }
            }
        }

        private bool CheckHasStaticPage(int shopid)
        {
            string path = Server.MapPath("~/shop/");
            string filepath = path + "index_" + shopid.ToString() + ".aspx";
            if (System.IO.File.Exists(filepath))
            {
                return true;
            }
            return false;
        }
    }
}